<template>
  <div class="menu-management">
    <h2>菜单管理</h2>

    <!-- 菜单列表 -->
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span>菜单列表</span>
          <div>
            <el-button type="primary" @click="handleAdd" size="small">新增菜单</el-button>
          </div>
        </div>
      </template>

      <!-- 查询条件 -->
      <el-form :inline="true" :model="queryForm" class="demo-form-inline">
        <el-form-item label="菜单名称">
          <el-input v-model="queryForm.name" placeholder="菜单名称" clearable></el-input>
        </el-form-item>
        <el-form-item label="路由路径">
          <el-input v-model="queryForm.path" placeholder="路由路径" clearable></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">查询</el-button>
          <el-button @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 菜单表格 -->
      <el-table :data="menuList" style="width: 100%" border>
        <el-table-column prop="id" label="ID" width="80"></el-table-column>
        <el-table-column prop="name" label="菜单名称"></el-table-column>
        <el-table-column prop="path" label="路由路径"></el-table-column>
        <el-table-column prop="component" label="组件路径"></el-table-column>
        <el-table-column prop="sort" label="排序" width="80"></el-table-column>
        <el-table-column label="操作" width="200">
          <template #default="scope">
            <el-button size="small" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button size="small" type="danger" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <el-pagination
          v-model:current-page="pagination.page"
          v-model:page-size="pagination.size"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          style="margin-top: 20px; justify-content: flex-end;"
      />

    </el-card>

    <!-- 菜单编辑对话框 -->
    <el-dialog
        :title="dialogTitle"
        v-model="dialogVisible"
        width="500px"
        @close="handleDialogClose"
    >
      <el-form :model="editForm" :rules="editRules" ref="editFormRef" label-width="100px">
        <el-form-item label="菜单名称" prop="name">
          <el-input v-model="editForm.name" placeholder="请输入菜单名称"></el-input>
        </el-form-item>
        <el-form-item label="路由路径" prop="path">
          <el-input v-model="editForm.path" placeholder="请输入路由路径"></el-input>
        </el-form-item>
        <el-form-item label="组件路径" prop="component">
          <el-input v-model="editForm.component" placeholder="请输入组件路径"></el-input>
        </el-form-item>
        <el-form-item label="父级菜单" prop="parentId">
          <el-select v-model="editForm.parentId" placeholder="请选择父级菜单" clearable style="width: 100%">
            <el-option label="无父级菜单" :value="null"></el-option>
            <el-option
                v-for="item in parentMenuOptions"
                :key="item.id"
                :label="item.name"
                :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input-number v-model="editForm.sort" :min="0" controls-position="right" style="width: 100%"/>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, reactive, computed } from 'vue';
import { MenuApi } from '@/api/menu.js';
import { ElMessage, ElMessageBox } from 'element-plus';

// 菜单列表数据
const menuList = ref([]);

// 查询表单
const queryForm = reactive({
  name: '',
  path: ''
});

// 分页参数
const pagination = reactive({
  page: 1,
  size: 10,
  total: 0
});

// 对话框相关
const dialogVisible = ref(false);      // 控制对话框的显示/隐藏
const dialogTitle = ref('');           // 存储对话框的标题
const isEdit = ref(false);             // 标记当前是编辑模式还是新增模式

// 编辑表单
const editForm = reactive({
  id: undefined,
  name: '',
  path: '',
  component: '',
  parentId: null,
  sort: 0
});

// 表单验证规则
const editRules = {
  name: [
    { required: true, message: '请输入菜单名称', trigger: 'blur' }
  ],
  path: [
    { required: true, message: '请输入路由路径', trigger: 'blur' }
  ],
  component: [
    { required: true, message: '请输入组件路径', trigger: 'blur' }
  ]
};

// 表单引用
const editFormRef = ref(null);

// 父级菜单选项
const parentMenuOptions = computed(() => {
  return menuList.value.filter(menu => !isEdit.value || menu.id !== editForm.id);
});

// 加载菜单列表数据（使用后端分页）
const loadMenuList = async () => {
  try {
    // 构建查询参数（包含分页参数）
    const params = {
      page: pagination.page,
      size: pagination.size
    };

    if (queryForm.name && queryForm.name.trim() !== '') {
      params.name = queryForm.name.trim();
    }
    if (queryForm.path && queryForm.path.trim() !== '') {
      params.path = queryForm.path.trim();
    }

    const res = await MenuApi.getMenuList(params);

    if (res && res.data) {
      menuList.value = res.data.records || res.data.list || [];

      // 关键修复：正确处理total值
      // 如果返回的数据等于或大于请求的size，说明可能还有更多数据
      if (menuList.value.length >= pagination.size) {
        // 估算total值：当前页之前的记录数 + 当前页记录数 + 1（表示还有更多数据）
        pagination.total = (pagination.page - 1) * pagination.size + menuList.value.length + 1;
      } else {
        // 如果返回的数据少于请求的size，说明这是最后一页
        pagination.total = (pagination.page - 1) * pagination.size + menuList.value.length;
      }
    } else {
      menuList.value = [];
      pagination.total = 0;
    }
  } catch (error) {
    console.error('获取菜单列表失败:', error);
    ElMessage.error('获取菜单列表失败');
    menuList.value = [];
    pagination.total = 0;
  }
};

// 查询按钮
const handleQuery = () => {
  pagination.page = 1;
  loadMenuList();
};

// 重置查询
const resetQuery = () => {
  queryForm.name = '';
  queryForm.path = '';
  pagination.page = 1;
  loadMenuList();
};

// 分页大小改变
const handleSizeChange = (val) => {
  pagination.size = val;
  pagination.page = 1; // 切换每页数量时重置到第一页
  loadMenuList();
};

// 当前页改变
const handleCurrentChange = (val) => {
  pagination.page = val;
  loadMenuList();
};

// 添加菜单
const handleAdd = () => {
  dialogTitle.value = '新增菜单';
  isEdit.value = false;
  resetEditForm();
  dialogVisible.value = true;
};

// 编辑菜单
const handleEdit = (row) => {
  dialogTitle.value = '编辑菜单';
  isEdit.value = true;
  Object.assign(editForm, row);
  dialogVisible.value = true;
};

// 删除菜单
const handleDelete = (row) => {
  ElMessageBox.confirm(
      `确定要删除菜单"${row.name}"吗？`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
  ).then(async () => {
    try {
      await MenuApi.deleteMenu(row.id);
      ElMessage.success('删除成功');
      loadMenuList(); // 重新加载列表
    } catch (error) {
      console.error('删除失败:', error);
      ElMessage.error(error.message || '删除失败');
    }
  }).catch(() => {
    ElMessage.info('已取消删除');
  });
};

// 重置编辑表单
const resetEditForm = () => {
  Object.assign(editForm, {
    id: undefined,
    name: '',
    path: '',
    component: '',
    parentId: null,
    sort: 0
  });
};

// 对话框关闭事件
const handleDialogClose = () => {
  resetEditForm();
  editFormRef.value?.resetFields();
};

// 提交表单
const submitForm = async () => {
  try {
    await editFormRef.value.validate();

    if (isEdit.value) {
      // 更新菜单
      const updateData = { ...editForm };
      const res = await MenuApi.updateMenu(updateData);
      ElMessage.success(res.data.message || '更新成功');
    } else {
      // 创建菜单
      const createData = { ...editForm };
      const res = await MenuApi.createMenu(createData);
      ElMessage.success(res.data.message || '创建成功');
    }

    dialogVisible.value = false;
    loadMenuList(); // 重新加载列表
  } catch (error) {
    console.error('操作失败:', error);
    ElMessage.error(error.message || (isEdit.value ? '更新失败' : '创建失败'));
  }
};

// 组件挂载时加载数据
onMounted(() => {
  loadMenuList();
});
</script>



<style scoped>
.menu-management {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.menu-node {
  display: flex;
  align-items: center;
  justify-content: space-between;
  width: 100%;
}

.menu-name {
  font-weight: 500;
}

.menu-info {
  margin-left: 20px;
}
</style>
